package com.al.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.al.entity.Student;
import com.al.service.StudentService;

@WebServlet("/student")
public class StudentController extends HttpServlet {
	StudentService studentService = new StudentService();
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String method = req.getParameter("method");
		switch(method) {
		case "update":
			String id = req.getParameter("id");
			String name = req.getParameter("name");
			String ageStr = req.getParameter("age");
			Integer age = Integer.parseInt(ageStr);
			String gender = req.getParameter("gender");
			String major = req.getParameter("major");
			String phoneStr = req.getParameter("phone");
			Long phone = Long.parseLong(phoneStr);
			studentService.upeate(id,name,age,gender,major,phone);
			break;
		case "add":
			id = req.getParameter("id");
			name = req.getParameter("name");
			ageStr = req.getParameter("age");
			age = Integer.parseInt(ageStr);
			gender = req.getParameter("gender");
			major = req.getParameter("major");
			phoneStr = req.getParameter("phone");
			phone = Long.parseLong(phoneStr);
			studentService.save(id,name,age,gender,major,phone);
			break;
		}
		//更新 list 集合中的数据，返回数据和集合，重定位到student，走get方法即可
		resp.sendRedirect("student");
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String method = req.getParameter("method");
		if(method == null || method.equals("null")) {
			method = "findAll";
		}
		switch(method) {
		case "findAll":
			//返回视图和数据
			List<Student> list = studentService.findAll();
			req.setAttribute("list", list);
			req.getRequestDispatcher("index.jsp").forward(req, resp);
			break;
		case "deleteById":
			String id = req.getParameter("id");
			studentService.deleteById(id);
			resp.sendRedirect("student");
			break;
		case "findById":
			id = req.getParameter("id");
			Student student = studentService.findById(id);
			req.setAttribute("student", student);
			req.getRequestDispatcher("update.jsp").forward(req, resp);
			break;
		}
		
	}
}
